let superagent = require('superagent')

//get http(s) promise
exports.gets = async function(url, data) {
  try {
    let { text, type } = await superagent.get(url).query(data)
    try {
      text = JSON.parse(text)
    } catch (error) {
      
    }
    return { suc: true, data: text }
  } catch (error) {
    return { suc: false, data: error }
  }
}

//post http(s) promise
exports.posts = async function(url, data) {
  data = JSON.stringify(data)

  return new Promise((resolve, reject) => {
    superagent
      .post(url)
      .send(data)
      .end((err, result) => {
        if (err) {
          resolve({ suc: false, data: err })
        }
        let data = result.body
        if (data.errcode) {
          resolve({ suc: false, data })
        } else {
          resolve({ suc: true, data })
        }
      })
  })
}

exports.send = function(res, { errcode, errmsg } = {}, data) {
  if (!data) {
    data = {}
  } else {
    for (let key in data) {
      if (typeof data[key] == 'undefined') {
        console.warn(`发送数据含未定义属性 ${data[key]}`)
        delete data[key]
      }
    }
  }
  data.errcode = errcode || 0
  data.errmsg = errmsg || 'ok'
  let jsonstr = JSON.stringify(data)
  res.send(jsonstr)
}
